﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Jack.RedisLib;

using Youshow.Ace.DependencyInjection;

namespace JackProjectTemplate.Cache.DistributedIdentifyGeneraters
{
    public class RedisUniqueIdentifyGenerater(IRedisClient redisClient) : IRedisUniqueIdentifyGenerater
    {
        private static readonly Random _random = new();

        public async Task<string> Generate(string identifyPrefix)
        {
            // 数字
            var num = _random.Next(1, 10_000);
            // 时间
            var time = DateTime.Now;
            // 唯一编号
            string identify = $"{identifyPrefix}{time:yyMMdd}{num:0000}{time:HHmmss}{Environment.CurrentManagedThreadId.ToString("00")[..2]}";

            // 判重
            if (await redisClient.StringIncrement(identify, 1) == 1)
            {
                await redisClient.KeyExpire(identify, TimeSpan.FromSeconds(3));
                return identify;
            }

            // 重复重新生成
            return await Generate(identifyPrefix);
        }
    }

    public interface IRedisUniqueIdentifyGenerater : ITransientDependency
    {
        Task<string> Generate(string identifyPrefix);
    }
}
